package com.softserveinc.moviedbapp.connection;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class InputStreamProvider {

	private int retryCount = 5;
	private static String TAG = InputStreamProvider.class.getSimpleName();

	private final URL movieApiUrl;

	/* constructor */
	public InputStreamProvider( final String movieApiUrl ) {
		try {
			this.movieApiUrl = new URL( movieApiUrl );
		} catch ( MalformedURLException e ) {
			throw new RuntimeException( e );
		}
	}

	public InputStream getInputStream() {

		Log.d( TAG, "inside getInputStream()" );

		while ( retryCount > 0 ) {
			try {
				return movieApiUrl.openConnection().getInputStream();
			} catch ( IOException e ) {
				retryCount--;
				Log.e( TAG, "failed to open an input stream. " + retryCount + " attemps left", e );
				continue;
			}
		}

		return null;
	}

	/* read JSON into a String */
	public String convertStreamToString( final InputStream is ) {

		BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ( ( line = reader.readLine() ) != null ) {
				sb.append( line + "\n" );
			}
		} catch ( IOException e ) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch ( IOException e ) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
